package com.atguigu.bigdata.scala.chapter07

object Scala12_Collection_WordCount_Test_2 {

    def main(args: Array[String]): Unit = {

        // TODO - WordCount

        // 集合的reduce方法的目的就是聚合数据，得到结果，也 可以称之为简化，规约
        val list = List(
            ("hello", 4),
            ("hello spark", 3),
            ("hello spark scala", 2),
            ("hello spark scala hive", 1)
        )
        val newlist = list.flatMap(
            t => {
                val str = t._1
                val cnt = t._2
                val words = str.split(" ")
                words.map(
                    word => {
                        (word, cnt)
                    }
                )
            }
        )
        val groups = newlist.groupBy(_._1)
        // // word => List((“hello”,1), (hello,2), (hello, 3)) => (Hello, 6)
        // reduce的参数类型： （A1, A1）=> A1
        val wordSum = groups.mapValues(
            list => {
                list.reduce(
                    (t1,t2)=>{
                        (t1._1, t1._2 + t2._2)
                    }
                )._2
            }
        )

        println(wordSum)
    }
}
